package com.hbpu.encap.houserent.service;

import com.hbpu.encap.houserent.domain.House;
import com.hbpu.encap.houserent.utils.Utility;

public class HouseService {
    private House[] houses = new House[2];
    private int idCounter = 1;
    public HouseService() {
        houses[0] = new House(1, "mike", "17678007383", "玉泉区", 1500, "未出租");
    }

    public House[] list() {
        return houses;
    }

    public void add(House house) {
        int count = 0;
        for (int i = 0; i < houses.length; i++) {
            if (houses[i] == null) {
                houses[i] = house;
                house.setId(++idCounter);
                System.out.println("添加成功！");
                break;
            }
            count++;
            if (count == houses.length) {
                expendArr();
            }
        }
    }

    private void expendArr() {
        House[] newHouse = new House[houses.length + 5];
        for (int i = 0; i < houses.length; i++) {
            newHouse[i] = houses[i];
        }
        houses = newHouse;
    }

    public void delete(int deleteID) {
        int index = -1;
        for (int i = 0; i < houses.length; i++) {
            if (houses[i].getId() == deleteID) {
                index = i;
                break;
            }
        }
        if (index != -1) {
            if (index == houses.length - 1 || index == 0) {
                houses[index] = null;
            } else {
                for (int i = index; i < houses.length && houses[i + 1] != null; i++) {
                    houses[i] = houses[i + 1];
                    houses[i + 1] = null;
                }
            }
            System.out.println("删除成功！");
        } else {
            System.out.println("未找到要删除房屋信息的id！");
        }
    }

    public House search(int searchID) {
        for (int i = 0; i < houses.length; i++) {
            if (houses[i].getId() == searchID) {
                return houses[i];
            }
        }
        return null;
    }

    public boolean update(House house) {
        if (house != null) {
            System.out.print("姓名(" + house.getName() + ")：");
            String name = Utility.readString(6, house.getName());
            house.setName(name);
            System.out.print("电话(" + house.getTel() + ")：");
            String tel = Utility.readString(11, house.getTel());
            house.setTel(tel);
            System.out.print("地址(" + house.getAddress() + ")：");
            String address = Utility.readString(10, house.getAddress());
            house.setAddress(address);
            System.out.print("租金(" + house.getRent() + ")：");
            int rent = Utility.readInt(house.getRent());
            house.setRent(rent);
            System.out.print("状态(" + house.getState() + ")：");
            String state  = Utility.readString(3, house.getState());
            house.setState(state);
            return true;
        } else {
            return false;
        }
    }
}
